<?php

namespace App\Http\Controllers\Api;

use App\Caches\WanSdkToApkTokenLoginCache;
use App\Http\Controllers\Controller;
use App\Models\Channels;
use App\Models\GameH5ToApkConfig;
use App\Models\Users;
use App\Services\WanSdk\WanSdkToApkService;
use Illuminate\Http\Request;

class H5ToApkController extends Controller
{
    public function canSwitch(Request $request)
    {
        $user_id         = $request->input('user_id');
        $server_id       = $request->input('server_id') ?? 0;
        $role_id         = $request->input('role_id');
        $game_channel_id = $request->input('game_channel_id');

        $data = [
            'can_switch' => 0,
        ];

        $user = Users::find($user_id);
        $config = GameH5ToApkConfig::whereRaw("game_id={$user->game_id} AND game_channel_id={$game_channel_id}")->first();
        if (!$config) {
            return yqok($data);
        }

        $ret = WanSdkToApkService::getInstance()->canSwitch($config, $user_id, $server_id, $role_id);
        if ($ret === false) {
            return yqok($data);
        }

        $data['can_switch']      = 1;
        $data['type']            = $config->type;
        $data['show_qrcode_url'] = $config->show_qrcode_url;
        $data['can_close']       = $config->can_close;
        $data['show_type']       = 1;
        if ($user->channel == Channels::CHANNEL_WXGAME) {
            $data['type'] = 1;
            $data['show_msg']  = '您的角色已达成领取宝箱条件，请尽快前往关注公众号联系客服领取';
        }

        return yqok($data);
    }

    public function getAccountByToken(Request $request)
    {
        $game_id = $request->input('game_id');
        $toapk_cache_id = $request->input('toapk_cache_id');
        $data = WanSdkToApkTokenLoginCache::getInstance()->get($toapk_cache_id);
        if (empty($data)) {
            return yqok();
        }

        // 记录转端时间
        $channel = Channels::CHANNEL_H5;
        $game_channel_id = $data['game_channel_id'];
        $account_openid = $data['account_openid'] ?? '';
        WanSdkToApkService::getInstance()->updateUserToApkInfo($game_id, $channel, $game_channel_id, $account_openid);

        WanSdkToApkTokenLoginCache::getInstance()->forget($toapk_cache_id);
        return yqok([
            'account'     => $data['account'] ?? '',
            'create_time' => $data['create_time'] ?? 0,
            'token'       => $data['token'] ?? '',
        ]);
    }
}
